#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
typedef long long LL;
const LL MOD=1000000007;
const LL MAXN=40007;
LL Fac[MAXN], RVS[MAXN], ReFac[MAXN];
LL POW(LL a, LL b) {
	LL res=1;
	LL M=a;
	while (b) {
		if (b&1) {
			res=(res*M)%MOD;
		}
		M=(M*M)%MOD;
		b=b>>1;
	}
	return res;
}
void Init() {
	Fac[0]=1; RVS[0]=1;
	for (LL i=1; i<MAXN; ++i) {
		Fac[i]=(Fac[i-1]*i)%MOD;
//		ReFac[i]=POW(Fac[i], MOD-2);
		if (i==1) RVS[i]=1;
		else RVS[i]=POW(i, MOD-2);
	}
}
LL S[MAXN];
LL Cha[MAXN];
vector<LL> map[MAXN]; 
LL DFS(LL root) {
	LL len=map[root].size();
	if (len==0) {
		S[root]=1;
		return 1;
	}
	LL all=0;
	for (LL i=0; i<len; ++i) {
		all+=DFS(map[root][i]);
	}
	++all;
	S[root]=all;
	return all;
}
LL m,n;
void MyDFS() {
	for (LL i=1; i<=m; ++i) {
		if (Cha[i]==i) DFS(i);
	}
}
int main() {
	Init();
	LL T;
	cin.sync_with_stdio(false);
	cin>>T;
	LL P, To;
	while (T--) {
		cin>>m>>n;
		for (LL i=0; i<=m; ++i) {
			map[i].clear();
			Cha[i]=i;
			S[i]=0;
		}
		for (LL i=0; i<n; ++i) {
			cin>>P>>To;
			Cha[P]=To;
			map[To].push_back(P);
		}
		MyDFS();
		LL ans=Fac[m];
		for (LL i=1; i<=m; ++i) ans=(ans*RVS[S[i]])%MOD;
		cout<<ans<<endl;
	}
	return 0;
}
